<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="指导单位" prop="college">
        <el-select
          v-model="queryParams.college"
          placeholder="请选择"
          clearable
          size="small"
        >
          <el-option
            v-for="(dict, index) in unitNameList"
            :key="index"
            :label="dict.sponsorName"
            :value="dict.sponsorName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="调研主题" prop="researchtopic">
        <el-select
          v-model="queryParams.researchtopic"
          placeholder="调研主题"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in researchtopics"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="applyExamined = true"
          v-hasPermi="['eqxm:examined:apply']"
          >发起年审</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          v-hasPermi="['eqxm:examined:downTemplate']"
          >下载模板</el-button
        >
        <!-- @click="inCollegeScoreOpen"  -->
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="handleExport"
          v-hasPermi="['eqxm:examined:export']"
          >导出</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      border
      v-loading="loading"
      :data="examinedList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        :selectable="selectable"
        width="50"
        align="center"
      />
      <el-table-column label="社团名称" align="center" prop="orgName" />
      <el-table-column label="指导单位" align="center" prop="units" />
      <el-table-column label="指导老师" align="center" prop="teacherName" />
      <el-table-column label="学生管理员" align="center" prop="studentManage" />
      <el-table-column label="社团联盟" align="center" prop="classNo" />

      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.examined_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
            <!-- v-show="scope.row.status == 3" -->
          <el-button
            v-hasPermi="['eqxm:examined:upload']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >上传材料</el-button
          >
          <el-button
            v-hasPermi="['eqxm:examined:examine']"
            v-show="scope.row.status == 0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="examineOpenF(scope.row)"
            >指导老师审核</el-button
          >
          <el-button
            v-hasPermi="['eqxm:examined:examine2']"
            v-show="scope.row.status == 1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="examineOpenF(scope.row)"
            >系统管理员审核</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改年审对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="系部" prop="college">
          <el-input v-model="form.college" placeholder="请输入系部" />
        </el-form-item>
        <el-form-item label="调研主题" prop="researchtopic">
          <el-input v-model="form.researchtopic" placeholder="请输入调研主题" />
        </el-form-item>
        <el-form-item label="是否重点" prop="isimportant">
          <el-input v-model="form.isimportant" placeholder="请输入是否重点" />
        </el-form-item>
        <el-form-item label="呈现形式" prop="presentation">
          <el-input v-model="form.presentation" placeholder="请输入呈现形式" />
        </el-form-item>
        <el-form-item label="呈现形式详情" prop="presentationdetail">
          <el-input
            v-model="form.presentationdetail"
            placeholder="请输入呈现形式详情"
          />
        </el-form-item>
        <el-form-item label="交通费" prop="transportation">
          <el-input v-model="form.transportation" placeholder="请输入交通费" />
        </el-form-item>
        <el-form-item label="住宿费" prop="accommodation">
          <el-input v-model="form.accommodation" placeholder="请输入住宿费" />
        </el-form-item>
        <el-form-item label="宣传费" prop="publicity">
          <el-input v-model="form.publicity" placeholder="请输入宣传费" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="录入系部成绩"
      :visible.sync="psOpen"
      width="500px"
      append-to-body
    >
      <el-table border :data="psList" @selection-change="handleSelectionChange">
        <el-table-column label="年审名称" align="center" prop="name" />
        <el-table-column label="分数" align="center" prop="collegeScore">
          <template slot-scope="scope">
            <el-input v-model.number="scope.row.collegeScore"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="psSubmitForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="上传材料"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        :action="uploadFileUrl"
        :limit="1"
        :on-exceed="handleExceed"
        :on-change="changeFile"
        :on-remove="removeFile"
        :on-error="handleUploadError"
        :on-success="handleUploadSuccess"
        :on-preview="dowloadFile"
        :file-list="meterialFileList"
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">
          只能上传doc、docx、xls、xlsx、txt文件,且大小不能超过35MB
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定1</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改年审对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="examineOpen"
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="审核意见" prop="reviewRejectedComments">
          <el-input
            v-model="reviewRejectedComments"
            placeholder="请输入审核意见"
          />
        </el-form-item>
        <el-button type="primary" @click="submitFormE('3')">审核拒绝</el-button>
        <el-button type="primary" @click="submitFormE('1')">审核通过</el-button>
      </el-form>
      <!--      <div slot="footer" class="dialog-footer">
	        <el-button type="primary" @click="submitForm">确 定</el-button>
	      </div> -->
    </el-dialog>

    <!-- 申请年审对话框 -->
    <el-dialog
      title="申请年审"
      :visible.sync="applyExamined"
      width="550px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="团队名称" prop="applyExaminedInfo">
          <el-select
            v-model="applyExaminedInfo"
            clearable
            size="small"
            style="width: 240px"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="getOrgList"
            :loading="searchLoading"
          >
            <el-option
              v-for="dict in examinedOptions"
              :key="dict.orgId"
              :label="dict.orgName"
              :value="dict"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="年审材料" prop="meterialFileList">
          <el-upload
            :action="uploadFileUrl"
            :limit="1"
            :on-exceed="handleExceed"
            :on-change="changeFile"
            :on-remove="removeFile"
            :on-error="handleUploadError"
            :on-success="handleUploadSuccess"
            :on-preview="dowloadFile"
            :file-list="meterialFileList"
          >
            <el-button size="small" type="primary">点击上传材料</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传doc、docx、xls、xlsx、txt文件,且大小不能超过35MB
            </div>
          </el-upload>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitExamined(3)">确 定</el-button>
        <el-button @click="close">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listExamined,
  //   getExamined,
  //   delExamined,
  addExamined,
  updateExamined,
  exportExamined,
  getUserExamined,
} from "@/api/examined/examined";
// import { getUserExamined } from '@/api/eqxm/examinedStudent';
// import CommonUtils from '@/utils/CommonUtils';
import { getToken } from "@/utils/auth";
export default {
  name: "Examined",
  dicts: ["examined_status"],
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 年审表格数据
      examinedList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      searchLoading: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // params:{
        // 	schoolSearch:"1",
        // },
        name: null,
        college: null,
        researchtopic: null,
        isimportant: null,
        presentation: null,
        presentationdetail: null,
        transportation: null,
        accommodation: null,
        publicity: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      recommendOptions: [],
      isHaveReviewRole: false,
      statuss: [],
      researchtopics: [],
      psOpen: false,
      psList: [],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData",
        college: "",
        fileChangeFlag: false,
        fileList: [],
        examinedid: "",
      },
      examineOpen: false,
      reviewRejectedComments: "",
      //年审弹框
      applyExamined: false,
      examinedOptions: [],
      applyExaminedInfo: null,
      unitNameList: [],

      uploadFileUrl: process.env.VUE_APP_BASE_API + "/api/images/uploadLocal",
      meterialFile: null,
      meterialFileList: [],
    };
  },
  created() {
    this.getList();
    // this.getDicts('recommend').then(response => {
    //   this.recommendOptions = response.data;
    // });
    this.getOrgList();
  },
  methods: {
    getOrgList(query) {
      var params = {
        pageNum: 1,
        pageSize: 20,
        type: 4,
        orgType: 4,
        orgName: query,
      };
      getUserExamined(params).then((response) => {
        console.log(response.rows, "res");
        this.examinedOptions = response.rows;
        //   if(this.examinedOptions.length>0){
        // 	  this.upload.college=this.examinedOptions[0].college;

        //   }
      });
    },
    // 判断多选是否禁用
    selectable(row, index) {
      if (this.examinedList[index].status == 0) {
        return true;
      } else {
        return false;
      }
    },
    /** 查询年审列表 */
    getList() {
      this.loading = true;
      //   console.log(this.queryParams,"this.queryParams")
      listExamined(this.queryParams).then((response) => {
        this.examinedList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        delFlag: null,
        college: null,
        createBy: null,
        researchtopic: null,
        isimportant: null,
        createTime: null,
        presentation: null,
        updateBy: null,
        presentationdetail: null,
        updateTime: null,
        transportation: null,
        accommodation: null,
        publicity: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 上传材料按钮操作 */
    handleUpdate(row) {
      // this.upload.fileList = [];
      // this.upload.id = row.id;
      // this.upload.title = "申请先进个人";
      // this.upload.open = true;
      this.$router.push({ path: '/examined/meterialFile', query: { id: row.id } });
    },
    // upload(row) {
    //   this.reset();
    //   let examinedInfo = {
    //     id: row.id,
    //   };
    //   CommonUtils.setCurExaminedInfo(examinedInfo);
    //   const vm = this;
    //   vm.$router.push({
    //     //核心语句
    //     path: "/examined/upload", //跳转的路径
    //     query: { type: 0 },
    //   });
    // },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateExamined(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addExamined(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除年审编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delExamined(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      var that = this;
      this.$confirm("是否确认导出所有年审数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          //   return exportExamined();
          console.log(queryParams, "queryParams");
          that.download(
            "/examined/export",
            { ...queryParams },
            `examined_${new Date().getTime()}.xlsx`
          );
          // return exportTeam(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    getHaveReviewRole() {
      getHaveReviewRole().then((response) => {
        this.isHaveReviewRole = response;
      });
    },
    recommendExamined() {
      const userIds = this.ids;
      if (userIds.length == 0) {
        this.$modal.msgError("请选择");
        return;
      }
      recommendExamined(userIds).then((response) => {
        this.$modal.msgSuccess("推荐成功");
        this.getList();
        this.open = false;
      });
    },
    inCollegeScoreOpen() {
      listPs().then((response) => {
        this.psList = response.data;
        this.loading = false;
        this.psOpen = true;
      });
    },
    psSubmitForm() {
      psSubmitForm(this.psList).then((response) => {
        this.$modal.msgSuccess("打分成功");
        this.getList();
        this.psOpen = false;
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    /** 文件移除时 */
    handleFileRemove(file, fileList) {
      this.upload.fileList = [];
      this.form.rcgcDocumentFileType = "";
    },
    // 文件改变时
    fileChange(file, fileList) {
      this.upload.fileChangeFlag = true;
      this.upload.fileList = fileList;
      //文件改变回填选中文件的类型
      let fileName = file.name;
      let type = fileName.split(".")[fileName.split(".").length - 1];

      this.form.rcgcDocumentFileType = type;
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1).toLowerCase();
      } else {
        return "";
      }
    },
    /** 提交按钮 */
    submitFileForm() {
      if (this.upload.fileList == null || this.upload.fileList.length <= 0) {
        this.$modal.msgError("请上传文件模板");
        return;
      }
      let fileSize = this.upload.fileList[0].size / (1024 * 1024);
      if (fileSize > 35) {
        this.$modal.msgError("上传文件过大，请重新选择文件上传");
        return false;
      }
      var testmsg = this.upload.fileList[0].name.substring(
        this.upload.fileList[0].name.lastIndexOf(".") + 1
      );
      const extension = testmsg === "xls";
      const extension2 = testmsg === "xlsx";
      const extension3 = testmsg === "doc";
      const extension4 = testmsg === "docx";
      const extension5 = testmsg === "txt";
      // const isLt2M = file.size / 1024 / 1024 < 10
      if (
        !extension &&
        !extension2 &&
        !extension3 &&
        !extension4 &&
        !extension5
      ) {
        this.$message({
          message: "只能上传doc、docx、xls、xlsx、txt格式的文件!",
          type: "warning",
        });
        return false;
      }

      let formData = new FormData();
      this.upload.fileList.forEach((file) => {
        formData.append("file", file.raw);
      });
      formData.append("college", this.upload.college);
      formData.append("id", this.upload.id);
      console.log(formData, "上传文件formData");
      ExaminedUpload(formData).then((response) => {
        this.$modal.msgSuccess("申请成功");
        this.upload.open = false;
        this.getList();
      });
    },
    /** 下载按钮操作 */
    examinedHandleDownload(row) {
      this.reset();
      const id = row.id || this.ids;
      downloadTemplateExamined(id).then((response) => {
        if (response != undefined || response != null) {
          if (response.data.size > 0) {
            let fileName = decodeURI(response.headers.contentfile);

            let contentType = "application/x-msdownload;";
            let blob = new Blob([response.data], {
              type: contentType + "charset=UTF-8",
            });
            if (window.navigator.msSaveOrOpenBlob) {
              //IE10+下载
              navigator.msSaveBlob(blob, fileName);
            } else {
              // 非IE下载
              var link = document.createElement("a");
              link.href = window.URL.createObjectURL(blob);
              link.download = fileName;
              link.click();
              //释放内存
              window.URL.revokeObjectURL(link.href);
            }
          }
        }
      });
    },
    // 申请年审
    submitExamined(res) {
      console.log(this.meterialFile, "this.meterialFile");
      // if (this.meterialFile && this.applyExaminedInfo.orgName) {
        console.log(this.applyExaminedInfo, "this.applyExamined");
        // 拷贝部分对象属性给另一个对象
        var { orgName, studentId, teacherId, teacherName, classNo } =
          this.applyExaminedInfo;
        var subForm = {
          orgName,
          studentId,
          teacherId,
          teacherName,
          classNo,
        };
        subForm.organizationId = this.applyExaminedInfo.orgId;
        subForm.units = this.applyExaminedInfo.unitName;
        subForm.studentManage = this.applyExaminedInfo.studentName;
        subForm.status = res;
        // subForm.document = this.meterialFile;
        console.log(subForm, "subForm");

        addExamined(subForm).then((response) => {
          if (response.code == 200) {
            this.$modal.msgSuccess("申请成功");
            this.getList();
            this.applyExamined = false;
          }
        });
      // } else {
      //   this.$modal.msgError("此两项数据必填！");
      // }
    },
    close() {
      this.meterialFile = null;
      this.meterialFileList = [];
      this.applyExamined = false;
      this.applyExaminedInfo = null;
    },
    examineOpenF(row) {
      this.form = row;
      this.form.creditExamineComments = "";
      this.examinedid = row.id;
      this.examineOpen = true;
    },
    // 审核
    submitFormE(res) {
      let subForm = {};
      subForm.status = res;
      // if(res=="3"){
      // subForm.onlineStatus = "0";
      // }
      subForm.reviewRejectedComments = this.reviewRejectedComments;
      subForm.id = this.examinedid;
      updateExamined(subForm).then((response) => {
        if (response.code == 200) {
          this.$modal.msgSuccess("审核成功");
          this.getList();
          this.examineOpen = false;
        }
      });
    },
    // 文件上传方法一系列----------------------------------------------------
    changeFile(file, fileList) {
      console.log(file.code, "change");
      if (file.status === "success") {
        console.log(file.response, "change");
        this.meterialFile = file.response.data.url;
        this.meterialFileList = fileList;
      }
    },
    removeFile() {
      this.meterialFile = null;
      this.meterialFileList = [];
    },
    // 文件上传是否成功
    handleUploadSuccess(res) {
      console.log(res, "resssss");
      if (res.code == 200) {
        this.$modal.msgSuccess("上传成功");
      } else {
        this.$modal.msgError("上传失败");
      }
    },
    handleUploadError() {
      this.$modal.msgError("上传失败");
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`数量超出，请先删除原附件!`);
    },
    //预览
    preview(fileName) {
      window.open(
        "https://ow365.cn/?i=29710&ssl=1&furl=" + process.env.VUE_APP_BASE_API + "/api/images/showLocal?name=" +
          fileName
      );
    },
    // 下载
    openUrl(fileName) {
      window.open(
        process.env.VUE_APP_BASE_API +`/api/images/showLocal?name=${fileName}`
      );
    },
    dowloadFile(file) {
      console.log(file, "file");
      this.openUrl(file.name);
    },
  },
};
</script>
